package com.infinit.selfhelp.common.base

import android.app.Dialog
import android.content.Context
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import com.infinit.selfhelp.common.R

class BaseDialog(val context: Context) {
    var view: View? = null
    private var isShowBottom = false
    private var canceledOnTouchOutside = true
    private var isMatchScreen = false
    fun setContent(view: View): BaseDialog {
        this.view = view
        return this
    }

    fun showBottom(): BaseDialog {
        isShowBottom = true
        return this
    }

    fun canceledOnTouchOutside(bool: Boolean): BaseDialog {
        canceledOnTouchOutside = bool
        return this
    }

    fun isMatchScreen(bool: Boolean): BaseDialog {
        isMatchScreen = bool
        return this
    }

    fun build(): Dialog {
        val dialog4 = Dialog(context, R.style.NormalDialogStyle)
        view?.let { dialog4.setContentView(it) }
        dialog4.setCanceledOnTouchOutside(canceledOnTouchOutside)
        val dialogWindow = dialog4.window //获取Dialog的窗口
        val lp = dialogWindow!!.attributes

        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        lp.width = displayMetrics.widthPixels - context.resources.getDimension(R.dimen.dp_24).toInt() //宽度铺满
        if(isMatchScreen){
            lp.height = WindowManager.LayoutParams.MATCH_PARENT //高度自适应
        }else{

            lp.height = WindowManager.LayoutParams.WRAP_CONTENT //高度自适应
        }
        if (isShowBottom) {
            lp.gravity = Gravity.BOTTOM //窗口停靠在底部居中
        }
        dialogWindow.setAttributes(lp)
        return dialog4
    }
}
